package com.guojian.jdbc.sql;

import java.util.Map;

import org.ehcache.impl.internal.concurrent.ConcurrentHashMap;
import org.springframework.util.Assert;

import com.alibaba.druid.sql.PagerUtils;
import com.guojian.jdbc.DBType;

/**
 * 
 * 采用Druid的sql解析
 * 
 * @author GuoJian
 *
 */
public class DruidSqlParser implements SqlParser {

	private static final Map<String, SqlParser> sqlParserMap = new ConcurrentHashMap<>();

	private String dbType;

	public DruidSqlParser(String dbType) {
		Assert.hasText(dbType, "数据库类型不能为空");
		this.dbType = dbType;
	}

	@Override
	public String getPageSql(String sql, Integer offset, Integer limit) {
		return PagerUtils.limit(sql, dbType, offset, limit);
	}

	@Override
	public String getCountSql(String sql) {
		return PagerUtils.count(sql, dbType);
	}

	public static void main(String[] args) {
		String sql = " SELECT * FROM user WHERE name = 'guojian' order by dt ";
		System.out.println(new DruidSqlParser("mysql").getCountSql(sql));
		System.out.println("==============");
		System.out.println(new DruidSqlParser("mysql").getPageSql(sql, 1, 2));

		System.out.println("=========================");

		System.out.println(get("mysql"));
		System.out.println(get("mysql"));
		System.out.println(get("oracle"));
		System.out.println(get("oracle"));
		System.out.println(get("sqlserver"));
		System.out.println(get("sqlserver"));

	}

	@Override
	public DBType getDBType() {
		return DBType.valueOf(this.dbType);
	}

	public static synchronized SqlParser get(String dbType) {
		return sqlParserMap.computeIfAbsent(dbType, (key) -> new DruidSqlParser(dbType));
	}

}
